import _ from "lodash";
import { message } from "antd";
let wantDeleteFatherKeys = [];
//隐藏列
export const hideColumns = async (sourceData, hideColumnKeyArr, hideColumnArr) => {
    const headerData = sourceData.header;
    //一. 去headerData 中把对应的 key 的节点移除
    removeHeader(headerData, hideColumnKeyArr);
    while (wantDeleteFatherKeys.length > 0) {
        removeHeader(headerData, wantDeleteFatherKeys);
    }
    //二. 去data中把对应的列数据删除
    // 1. 获取隐藏列的下标
    let hideColumnDataIndexArr = hideColumnArr;
    // 2. 把对应下标的data删除
    const tableData = sourceData.data;
    for (let i = 0; i < tableData.length; i++) {
        let tableRowData = tableData[i];
        tableRowData = tableRowData.filter((item, index) => !hideColumnDataIndexArr?.includes(index));
        tableData[i] = tableRowData;
    }
    // 三. 修改 cellMetaData
    //1. 删除隐藏的单元格样式对象
    const cellMetaData = sourceData.cellsMeta;
    for (let j = 0; j < hideColumnDataIndexArr?.length; j++) {
        const hidenColumnIndex = hideColumnDataIndexArr?.[j];
        // 1.删除隐藏列的cellMeta对象
        for (let i = 0; i < cellMetaData.length; i++) {
            const cellMetaItem = cellMetaData[i];
            if (cellMetaItem.col === hidenColumnIndex) {
                cellMetaData.splice(i, 1);
            }
        }
    }
    //2. 修改col的值
    for (let i = 0; i < cellMetaData.length; i++) {
        const cellMetaItem = cellMetaData[i];
        //计算向左移动几个
        let move = 0;
        for (let j = 0; j < hideColumnDataIndexArr.length; j++) {
            const hideColumnDataIndex = hideColumnDataIndexArr[j]; // 3
            if (cellMetaItem.col > hideColumnDataIndex) {
                move++;
            }
        }
        cellMetaItem.col = cellMetaItem.col - move;
    }
    // 隐藏完毕以后刷新table
    const igridData = {
        header: headerData,
        data: tableData,
        cellsMeta: cellMetaData,
        tableConfig: sourceData.tableConfig,
    };
    return igridData;
};
export const removeHeader = (headerData, hideColumnKeyArr, fatherNode) => {
    for (let i = 0; i < headerData.length;) {
        let isDelete = false;
        const headerDataItem = headerData[i];
        if (hideColumnKeyArr.includes(headerDataItem.key)) {
            const deletedObjArr = headerData.splice(i, 1); //
            const deleteObjKey = deletedObjArr[0].key;
            // 删完后从待删除数组中移除该元素
            wantDeleteFatherKeys = wantDeleteFatherKeys.filter((item) => item !== deleteObjKey);
            isDelete = true;
            if (headerData.length === 0) {
                // 子元素数组删空了 同时删除父元素
                wantDeleteFatherKeys.push(fatherNode.key);
            }
        }
        else if (headerDataItem.children && headerDataItem.children.length > 0) {
            // 复合列
            const children = headerDataItem.children;
            removeHeader(children, hideColumnKeyArr, headerDataItem);
        }
        if (!isDelete) {
            // 因为删除数组元素后，数组长度变了，如果i再加1的话 会少遍历一个元素，所以当删除元素时i不能加1
            i++;
        }
    }
};
/**
 * 功能： 拆表
 * @param cpasData 原表的 gridData
 * @param rule 拆表规则 例如 2,3,3
 * @returns 拆完后的 gridData 的数组
 */
export const divideTable = (cpasData, ruleStr) => {
    const leafNodeArr = [];
    const gridDataArr = [];
    const setFatherKey = (headerColumn) => {
        if (headerColumn.children && headerColumn.children.length > 0) {
            let children = headerColumn.children;
            for (let j = 0, childrenLength = children.length; j < childrenLength; j++) {
                let child = children[j];
                child.fatherKey = headerColumn.key;
                child.fatherNode = headerColumn;
                setFatherKey(child);
            }
        }
        else {
            headerColumn.leafNode = true;
            leafNodeArr.push(headerColumn); // 2.树型结构-----> 线性结构
        }
    };
    const addFatherKeyToHeader = (header) => {
        // 遍历每个节点 如果节点有children ,遍历孩子 给孩子设置fatherKey为父节点的key
        for (let i = 0, headerLength = header.length; i < headerLength; i++) {
            if (i === 0 || i === headerLength - 1)
                continue;
            const headerColumn = header[i];
            setFatherKey(headerColumn);
        }
        for (let i = 0, headerLength = header.length; i < headerLength; i++) {
            if (i === 0 || i === headerLength - 1)
                continue;
        }
    };
    /**
      把单元格样式一维数组形式转换成类似data的二维数组形式
    */
    const changeCellsMeta = (cellsMeta) => {
        let cellMetaArr;
        if (cellsMeta.length > 0) {
            // 用户有设置单元格样式
            const cellMetaArrLength = cellsMeta[0].row;
            cellMetaArr = new Array(cellMetaArrLength);
            for (let i = 0; i < cellMetaArr.length; i++) {
                cellMetaArr[i] = [];
            }
            for (let i = cellsMeta.length - 1; i >= 0; i--) {
                const cellMetaObj = cellsMeta[i];
                const row = cellMetaObj.row;
                const col = cellMetaObj.col;
                cellMetaArr[row - 1][col - 1] = cellMetaObj;
            }
        }
        return cellMetaArr;
    };
    const dismantleTable = (leafNodeArr, ruleStr, cpasDataCopy) => {
        let rule = ruleStr.split(",");
        let dismantleTableMode;
        if (sessionStorage.dismantleTableMode) {
            dismantleTableMode = JSON.parse(sessionStorage.dismantleTableMode);
        }
        if (dismantleTableMode && sessionStorage.cpasData) {
            // cpasData = JSON.parse(sessionStorage.cpasData);
            // console.log('看这里对不对cpasData', cpasData);
        }
        else {
            //cpasData = this.context.gridRef.getCpasTableGrid();
            cpasData = cpasDataCopy; // 如果不使用 cpasDataCopy 下面这行会报循环转换错误
            sessionStorage.cpasData = JSON.stringify(cpasData);
        }
        const tableData = cpasData.data;
        //1.把单元格样式一维数组转换成二维数组
        const cellsMeta = cpasData.cellsMeta;
        const cellMetaArr = changeCellsMeta(cellsMeta);
        const tableDataWithoutFirstAndLastColumn = []; // 不带第一列隐藏列和最后一列隐藏列的表数据
        const realColumnDataLength = tableData[0].length;
        if (rule.length < 2) {
            message.info("至少输入两个参数");
            return;
        }
        // 必须都为数字
        for (let i = 0; i < rule.length; i++) {
            const ruleItem = rule[i];
            if (isNaN(ruleItem)) {
                message.info("参数必须都要是数字");
                return;
            }
        }
        for (let i = 0; i < tableData.length; i++) {
            let rowData = tableData[i];
            rowData = rowData.filter((item, index) => index != 0 && index != realColumnDataLength - 1);
            tableDataWithoutFirstAndLastColumn.push(rowData);
        }
        // ------------添加处理隐藏列的兼容代码----------------
        // if (dismantleTableMode) {
        //   this.context.hideColumnKeyArr = JSON.parse(
        //     sessionStorage.hideColumnKeyArr
        //   );
        // }
        // if (this.context.hideColumnKeyArr.length > 0) {
        //   // 剔除 header 中的隐藏列
        //   const needRemoveHiddenColumnDataColumnIndexArr = [];
        //   leafNodeArr = leafNodeArr.filter((item, index) => {
        //     const isHiddenColumnFlag = this.context.hideColumnKeyArr.includes(
        //       item.key
        //     );
        //     if (isHiddenColumnFlag) {
        //       needRemoveHiddenColumnDataColumnIndexArr.push(index);
        //     }
        //     return !isHiddenColumnFlag;
        //   });
        //   // 剔除 data 中的隐藏列
        //   for (let i = 0; i < tableDataWithoutFirstAndLastColumn.length; i++) {
        //     let rowData = tableDataWithoutFirstAndLastColumn[i];
        //     rowData = rowData.filter(
        //       (item, index) =>
        //         !needRemoveHiddenColumnDataColumnIndexArr.includes(index)
        //     );
        //     tableDataWithoutFirstAndLastColumn[i] = rowData;
        //   }
        // 剔除 cellMetaArr 中的隐藏列
        // for (let i = 0; i < cellMetaArr?.length; i++) {
        //   let rowCellMeta = cellMetaArr[i];
        //   rowCellMeta = rowCellMeta.filter(
        //     (item, index) =>
        //       !needRemoveHiddenColumnDataColumnIndexArr.includes(index)
        //   );
        //   cellMetaArr[i] = rowCellMeta;
        // }
        //}
        const leafNodeArrLength = leafNodeArr.length;
        const columnIndexThatEveryTableHas = rule[0]; // 2 表示前两列每张表都要有
        let columnHeaderThatEveryTableHas = []; // 每张表都要有的列头
        let columnDataThatEveryTableHas = []; // 每张表都要有的列数据
        let cellMetaDataThatEveryTableHas = []; // 每张表都要有的列单元格样式数据
        let columnHeaderThatSingleTableHas = []; // 二维数组 第一个元素存放第一张表的列头信息，第二个元素存放第二张表的列头信息，依次类推
        let columnDataThatSingleTableHas = []; // 三维数组 存放每张表的列数据 每张表的列数据是一个二维数组 第一个元素存放第一张表的列数据，第二个元素存放第二张表的列数据，依次类推
        let cellMetaDataThatSingleTableHas = []; // 三维数组 每个元素都是一个二维数组 存放该表自己的单元格样式  0 表示第一张表的 1表示第2张表的
        if (columnIndexThatEveryTableHas < 0 ||
            columnIndexThatEveryTableHas >= leafNodeArrLength) {
            message.info("第一个参数（每张表都要有的列）必须大于等于0且小于表的列数");
            return;
        }
        // this.context.gridRef.tableConfig.rule = ruleStr;
        // this.context.gridRef.tableConfig.dismantleTableMode = true;
        // 开始拆表
        if (columnIndexThatEveryTableHas > 0) {
            // 取每张表都有的列头
            columnHeaderThatEveryTableHas = leafNodeArr.splice(0, columnIndexThatEveryTableHas);
            // 取每张表都有的列数据
            for (let i = 0; i < tableDataWithoutFirstAndLastColumn.length; i++) {
                const rowData = tableDataWithoutFirstAndLastColumn[i];
                const rowDataThatEveryTableHas = rowData.splice(0, columnIndexThatEveryTableHas);
                columnDataThatEveryTableHas.push(rowDataThatEveryTableHas);
            }
            // 取每张表都有的列单元格数据
            for (let i = 0; i < cellMetaArr?.length; i++) {
                const rowCellMetaData = cellMetaArr[i];
                const rowCellMetaDataThatEveryTableHas = rowCellMetaData.splice(0, columnIndexThatEveryTableHas);
                cellMetaDataThatEveryTableHas.push(rowCellMetaDataThatEveryTableHas);
            }
        }
        let leftColumnCount = leafNodeArrLength - columnIndexThatEveryTableHas; // 11 - 1 = 10
        for (let i = 1; i <= rule.length - 1;) {
            const ruleItem = rule[i]; // i=1 时 表示第一表的列取几个  i=1 值是2    i=2 为4   i=3为3
            if (ruleItem <= 0) {
                message.info("每张表的列个数必须大于0");
                return;
            }
            if (leftColumnCount > 0) {
                // 给拆出的每张表取自己的列头
                const slicedColumnHeader = leafNodeArr.splice(0, ruleItem);
                columnHeaderThatSingleTableHas.push(slicedColumnHeader);
                // 给拆出的每张表取自己的列数据
                const singleTableData = []; // 单表数据
                for (let j = 0; j < tableDataWithoutFirstAndLastColumn.length; j++) {
                    const rowData = tableDataWithoutFirstAndLastColumn[j];
                    const slicedColumnData = rowData.splice(0, ruleItem);
                    singleTableData.push(slicedColumnData);
                }
                columnDataThatSingleTableHas.push(singleTableData);
                // 给拆出的每张表取自己的列单元格样式数据
                const singleTableCellMetaData = []; // 单表的单元格样式数据
                for (let j = 0; j < cellMetaArr?.length; j++) {
                    const rowCellMetaData = cellMetaArr[j];
                    const slicedColumnCellMetaData = rowCellMetaData.splice(0, ruleItem);
                    singleTableCellMetaData.push(slicedColumnCellMetaData);
                }
                cellMetaDataThatSingleTableHas.push(singleTableCellMetaData);
                leftColumnCount = leftColumnCount - ruleItem; // 1
                if (i != rule.length - 1)
                    i++;
            }
            else {
                break;
            }
        }
        cpasData.tableConfig = { a: 1 };
        return {
            columnHeaderThatEveryTableHas,
            columnDataThatEveryTableHas,
            cellMetaDataThatEveryTableHas,
            columnHeaderThatSingleTableHas,
            columnDataThatSingleTableHas,
            cellMetaDataThatSingleTableHas,
        };
    };
    const assembleData = (data) => {
        const { columnHeaderThatEveryTableHas, columnDataThatEveryTableHas, cellMetaDataThatEveryTableHas, columnHeaderThatSingleTableHas, columnDataThatSingleTableHas, cellMetaDataThatSingleTableHas, } = data;
        const tableCount = columnHeaderThatSingleTableHas.length;
        //const cpasData = cpasDataCopy;
        const tableData = cpasData.data;
        const tableHeader = cpasData.header;
        const firstColumn = tableHeader[0];
        const lastColumn = tableHeader[tableHeader.length - 1];
        const generateCellsMeta = (tableIndex) => {
            const data = []; // 二维数组
            const singleTableCellMetaData = cellMetaDataThatSingleTableHas[tableIndex]; // 取单表列数据
            for (let row = 0; row < cellMetaDataThatEveryTableHas.length; row++) {
                const rowCellMetaDataEvery = cellMetaDataThatEveryTableHas[row];
                const rowCellMetaDataSingle = singleTableCellMetaData[row];
                let finalColumnDigit = 1;
                for (let i = 0; i < rowCellMetaDataEvery.length; i++) {
                    const cellMetaOne = rowCellMetaDataEvery[i];
                    cellMetaOne.col = finalColumnDigit;
                    finalColumnDigit++;
                    data.push(cellMetaOne);
                }
                for (let j = 0; j < rowCellMetaDataSingle.length; j++) {
                    const cellMetaOne = rowCellMetaDataSingle[j];
                    cellMetaOne.col = finalColumnDigit;
                    finalColumnDigit++;
                    data.push(cellMetaOne);
                }
            }
            return data;
        };
        const generateData = (tableIndex) => {
            const data = []; // 二维数组
            const singleTableColumnData = columnDataThatSingleTableHas[tableIndex]; // 取单表列数据
            for (let i = 0; i < tableData.length; i++) {
                const orginalRowData = tableData[i];
                const firstColumnData = orginalRowData[0];
                const lastColumnData = orginalRowData[orginalRowData.length - 1];
                // 第一个隐藏列数据 + 每张表都要有的列数据 + 自己独有的列数据 + 最后一个隐藏列数据
                let finishedRowData;
                if (columnDataThatEveryTableHas.length > 0) {
                    finishedRowData = [
                        firstColumnData,
                        ...columnDataThatEveryTableHas[i],
                        ...singleTableColumnData[i],
                        lastColumnData,
                    ];
                }
                else {
                    finishedRowData = [
                        firstColumnData,
                        ...singleTableColumnData[i],
                        lastColumnData,
                    ];
                }
                data.push(finishedRowData);
            }
            return data;
        };
        const generateHeader = (tableIndex) => {
            const header = [firstColumn];
            // 中间添加每张表的header
            const singleTableColumnHeader = columnHeaderThatSingleTableHas[tableIndex];
            const finalEveryTableColumnHeader = [
                ...columnHeaderThatEveryTableHas,
                ...singleTableColumnHeader,
            ];
            const needLeftNodeKeySet = new Set(); // 存需要留下的节点的key
            const needLeftNodeLabelSet = new Set(); // 存需要留下的节点的key
            const headerRootNodeArr = [];
            for (let i = 0; i < finalEveryTableColumnHeader.length; i++) {
                const columnHeaderInfo = finalEveryTableColumnHeader[i];
                const fatherKey = columnHeaderInfo.fatherKey;
                if (!fatherKey) {
                    // 根节点直接添加到 header中
                    // header.push(columnHeaderInfo);
                    headerRootNodeArr.push(columnHeaderInfo);
                }
                else {
                    // 处理非根节点
                    needLeftNodeKeySet.add(columnHeaderInfo.key); // 加31
                    needLeftNodeLabelSet.add(columnHeaderInfo.label);
                    // 把该节点的所有父亲的key加进去
                    let tempNode = columnHeaderInfo;
                    while (tempNode.fatherKey) {
                        needLeftNodeKeySet.add(tempNode.fatherNode.key); // 加21 加11
                        needLeftNodeLabelSet.add(tempNode.fatherNode.label);
                        tempNode = tempNode.fatherNode;
                    }
                    // 看headerRootNodeArr 有没有重复的 headerRoot
                    let sameFlag = false;
                    for (let j = 0; j < headerRootNodeArr.length; j++) {
                        const headerRootNode = headerRootNodeArr[j];
                        if (headerRootNode.key === tempNode.key) {
                            sameFlag = true;
                        }
                    }
                    if (!sameFlag) {
                        headerRootNodeArr.push(tempNode);
                    }
                }
            }
            const needLeftNodeKeyArr = [...needLeftNodeKeySet];
            const deleteNoExistChildNode = (singleNode) => {
                if (singleNode && singleNode.children) {
                    let children = singleNode.children;
                    // 从children中移除没有的节点
                    children = children.filter((item) => needLeftNodeKeyArr.includes(item.key));
                    for (let i = 0; i < children.length; i++) {
                        deleteNoExistChildNode(children[i]);
                    }
                    singleNode.children = children;
                }
            };
            // 深拷贝 headerRootNodeArr
            const headerRootNodeArr2 = _.cloneDeep(headerRootNodeArr);
            // 剔除 headerRootNodeArr2 中没有的子节点
            for (let i = 0; i < headerRootNodeArr2.length; i++) {
                const singleNode = headerRootNodeArr2[i];
                deleteNoExistChildNode(singleNode);
            }
            // 剔除所有节点的fatherNode
            const removeFatherNode = (headerRootNodeArr2) => {
                for (let i = 0; i < headerRootNodeArr2.length; i++) {
                    let singleNode = headerRootNodeArr2[i];
                    if (singleNode.fatherNode)
                        delete singleNode.fatherNode;
                    if (singleNode.children) {
                        removeFatherNode(singleNode.children);
                    }
                }
            };
            removeFatherNode(headerRootNodeArr2);
            for (let i = 0; i < headerRootNodeArr2.length; i++) {
                const headerItem = headerRootNodeArr2[i];
                header.push(headerItem);
            }
            header.push(lastColumn);
            return header;
        };
        for (let tableIndex = 0; tableIndex < tableCount; tableIndex++) {
            // 构件每张表的gridData
            const gridData = {};
            const data = generateData(tableIndex); // (1) 构建data
            const header = generateHeader(tableIndex);
            const cellsMeta = generateCellsMeta(tableIndex);
            console.log(`第${tableIndex + 1}张表的数据`);
            const tableConfig = {};
            gridData.header = header;
            gridData.data = data;
            gridData.cellsMeta = cellsMeta;
            gridData.tableConfig = {};
            gridDataArr.push(gridData);
        }
    };
    const cpasDataCopy = _.cloneDeep(cpasData);
    const header = cpasData.header;
    // 1. 给节点加父亲的 key 和 2. 树型结构-----> 线性结构
    addFatherKeyToHeader(header);
    // 2. 拆表
    const result = dismantleTable(leafNodeArr, ruleStr, cpasDataCopy);
    // 3. 组装成三表的数据 线性结构--->树型结构
    if (result) {
        assembleData(result);
    }
    return gridDataArr;
};
